using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.CompositeWeb;
using CompositeWeb.Extensions.Services;
using CompositeWeb.Extensions.Interfaces;
using Microsoft.Practices.CompositeWeb.Interfaces;
using CompositeWeb.Extensions.Utility;
using System.Web.UI;

namespace CompositeWeb.Extensions
{
    public class ExtendedWebClientApplication : WebClientApplication
    {
        private UserControlInjectionUtility _userControlInjectionUtility;

        public ExtendedWebClientApplication()
            : this(new UserControlInjectionUtility())
        {
        }

        public ExtendedWebClientApplication(UserControlInjectionUtility utility)
        {
            _userControlInjectionUtility = utility;
        }
        
        protected override void AddRequiredServices()
        {
            RegisterServices(this.RootContainer);

            base.AddRequiredServices();
        }

        public static void RegisterServices(ICompositionContainer rootContainer)
        {
            rootContainer.Services.AddNew<WebConfigModuleInfoStore, ICustomModuleInfoStore>();
            rootContainer.Services.AddNew<WebModuleEnumerator, IModuleEnumerator>();
            rootContainer.Services.AddNew<ModuleLoaderService, IModuleLoaderService>();

            rootContainer.Services.AddNew<ServiceLoader, IServiceLoader>();
        }

        protected override void PrePageExecute(Page page)
        {
            base.PrePageExecute(page);
            _userControlInjectionUtility.PrePageExecute(
                page,
                GetModuleContainer(new Microsoft.Practices.CompositeWeb.Web.HttpContext(System.Web.HttpContext.Current)),
                this.PageBuilder);
        }

        protected override void PostPageExecute(Page page)
        {
            base.PostPageExecute(page);
            _userControlInjectionUtility.PostPageExecute(
                page,
                GetModuleContainer(new Microsoft.Practices.CompositeWeb.Web.HttpContext(System.Web.HttpContext.Current)),
                this.PageBuilder);
        }
    }
}
